package com.dlc.shop.user.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dlc.shop.bean.enums.DeliveryType;
import com.dlc.shop.bean.enums.OrderStatus;
import com.dlc.shop.bean.enums.OrderType;
import com.dlc.shop.bean.enums.RefundStatusEnum;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.model.UserAddrOrder;
import com.dlc.shop.bean.param.DeliveryOrderParam;
import com.dlc.shop.bean.param.OrderParam;
import com.dlc.shop.bean.vo.UnDeliveryOrderExcelVO;
import com.dlc.shop.common.config.Constant;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.PageParam;
import com.dlc.shop.delivery.common.param.DeliveryOrderItemParam;
import com.dlc.shop.delivery.common.service.DeliveryOrderService;
import com.dlc.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author lgh on 2018/09/15.
 */
@Tag(name = "积分订单")
@RestController
@RequestMapping("/score/order")
@AllArgsConstructor
public class ScoreOrderController {

    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final UserAddrOrderService userAddrOrderService;
    private final ProductService productService;
    private final SkuService skuService;
    private final OrderExcelService orderExcelService;
    private final DeliveryOrderService deliveryOrderService;

    @GetMapping("/page")
    @Operation(summary = "分页获取" , description = "分页获取")
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:page')")
    public ServerResponseEntity<IPage<Order>> page(OrderParam orderParam, PageParam<Order> page) {
        orderParam.setShopId(Constant.PLATFORM_SHOP_ID);
        orderParam.setOrderType(OrderType.SCORE.value());
        IPage<Order> orderPage = orderService.pageOrdersDetailByOrderParam(page, orderParam);
        for (Order order : orderPage.getRecords()) {
            order.setShopName("官方店");
        }
        return ServerResponseEntity.success(orderPage);
    }

    @GetMapping("/orderInfo/{orderNumber}")
    @Operation(summary = "获取信息" , description = "获取信息")
    @Parameter(name = "orderNumber", description = "订单编号" )
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:info')")
    public ServerResponseEntity<Order> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber,shopId,true);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber,false);
        order.setOrderItems(orderItems);
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        return ServerResponseEntity.success(order);
    }

    @PutMapping("/delivery")
    @Operation(summary = "商品发货" , description = "商品发货")
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:delivery')")
    public ServerResponseEntity<Void> delivery(@RequestBody DeliveryOrderParam deliveryOrderParam) {
        Long shopId = Constant.PLATFORM_SHOP_ID;
        Order order = orderService.getOrderByOrderNumberAndShopId(deliveryOrderParam.getOrderNumber(),shopId,true);

        if (Objects.equals(order.getRefundStatus(), RefundStatusEnum.APPLY.value())) {
            // 该订单有退款信息正在处理当中，请处理完毕之后再进行发货的操作
            throw new YamiShopBindException("yami.order.delivery.refund.error！");
        }
        if (!Objects.equals(order.getStatus(), OrderStatus.PADYED.value())){
            // 订单不处于待发货状态，无法进行发货
            throw new YamiShopBindException("yami.order.delivery.no.right");
        }

        Order orderParam = new Order();
        orderParam.setOrderId(order.getOrderId());
        orderParam.setDvyId(deliveryOrderParam.getDvyId());
        orderParam.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        orderParam.setDvyTime(new Date());
        orderParam.setUpdateTime(new Date());
        orderParam.setStatus(OrderStatus.CONSIGNMENT.value());
        orderParam.setUserId(order.getUserId());

        orderService.delivery(orderParam);

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(deliveryOrderParam.getOrderNumber(),false);
        for (OrderItem orderItem : orderItems) {
            productService.removeProdCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
        }
        return ServerResponseEntity.success();
    }

    @GetMapping("/soldExcel")
    @Operation(summary = "导出订单" , description = "导出订单")
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:exportOrder')")
    public void soldExcel(OrderParam orderParam, HttpServletResponse response) {
        orderParam.setOrderType(OrderType.SCORE.value());
        orderExcelService.soldExcel(orderParam,response);

    }

    /**
     * 导出待发货订单
     * @param orderParam
     * @param response
     */
    @GetMapping("/unDeliveryOrderExcel")
    @Operation(summary = "导出待发货订单")
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:exportUnDeliveryOrder')")
    public void unDeliveryOrderExcel(OrderParam orderParam, HttpServletResponse response) {
        orderParam.setShopId(Constant.PLATFORM_SHOP_ID);
        orderParam.setOrderType(OrderType.SCORE.value());
        orderExcelService.unDeliveryOrderExcel(orderParam, response);
    }


    @PostMapping("/exportOrderExcel")
    @Operation(summary = "导入待发货文件")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('user:scoreOrder:importUnDeliveryOrder')")
    public ServerResponseEntity<String> exportOrderExcel(@RequestParam("orderExcelFile") MultipartFile orderExcelFile) throws Exception {
        if (Objects.isNull(orderExcelFile)) {
            throw new YamiShopBindException("yami.network.busy");
        }
        List<UnDeliveryOrderExcelVO> orderList = new ArrayList<>();
        String errorMsg = orderExcelService.exportOrderExcel(orderExcelFile, Constant.PLATFORM_SHOP_ID, orderList);
        if (Objects.nonNull(errorMsg)) {
            return ServerResponseEntity.success(errorMsg);
        }
        //无错误再发货
        for (UnDeliveryOrderExcelVO orderExcelVO : orderList) {
            DeliveryOrderItemParam deliveryOrderParam = new DeliveryOrderItemParam();
            deliveryOrderParam.setOrderNumber(orderExcelVO.getOrderNumber());
            deliveryOrderParam.setDeliveryType(orderExcelVO.getDvyType());
            if (Objects.equals(orderExcelVO.getDvyType(), DeliveryType.EXPRESS.getValue())) {
                deliveryOrderParam.setDvyFlowId(orderExcelVO.getDvyFlowId());
                deliveryOrderParam.setDvyId(orderExcelVO.getDvyId());
            }
            List<OrderItem> selectOrderItems = new ArrayList<>();
            for (OrderItem orderItem : orderExcelVO.getOrderItemList()) {
                OrderItem deliveryItem = new OrderItem();
                deliveryItem.setOrderItemId(orderItem.getOrderItemId());
                deliveryItem.setChangeNum(orderItem.getStatus() == -1 ? orderItem.getChangeNum() : orderItem.getStatus());
                deliveryItem.setStatus(orderItem.getStatus());
                deliveryItem.setProdCount(orderItem.getChangeNum());
                selectOrderItems.add(deliveryItem);
            }
            deliveryOrderParam.setSelectOrderItems(selectOrderItems);
            deliveryOrderService.saveDeliveriesInfo(deliveryOrderParam, Constant.PLATFORM_SHOP_ID);
        }
        return ServerResponseEntity.success("导入成功！");
    }

}
